#include <stdio.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>

SDL_Window *window;
SDL_Renderer *render;
TTF_Font *font;

typedef struct _TEXT_TEXTURE
{
    SDL_Texture *txtText;
    SDL_Rect txtDstRect;
} TEXT_TEXTURE;
TEXT_TEXTURE txtText1;
SDL_Color textColor = {255, 0, 0, 255};
int init()
{
    int ret = 1;
    if (TTF_Init() == -1)
    {
        printf("TTF unable to initialize! Error: %s\n", TTF_GetError());
        ret = 0;
    }
    if (SDL_Init(SDL_INIT_VIDEO) < 0)
    {
        printf("sdl could not init!sdl error:%s\n", SDL_GetError());
        ret = 0;
    }
    else
    {
        if ((window = SDL_CreateWindow("sdl", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 400, 300, 0)) == NULL)
        {
            printf("could not create! error:%s\n", SDL_GetError());
            ret = 0;
        }
        else
        {
            if ((render = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED)) == NULL)
            {
                printf("render could not create! error:%s\n", SDL_GetError());
                ret = 0;
            }
        }
    }
    return ret;
}
void setTextTexture(TEXT_TEXTURE *txtText, TTF_Font *font, char *text)
{
    // Render text surface
    SDL_Surface *textSurface = TTF_RenderUTF8_Blended(font, text, textColor);
    SDL_DestroyTexture(txtText->txtText);
    // Create texture from surface pixels
    txtText->txtText = SDL_CreateTextureFromSurface(render, textSurface);
    txtText->txtDstRect = (SDL_Rect){0, 0, textSurface->w, textSurface->h};
    // Get rid of the obsolete surface
    SDL_FreeSurface(textSurface);
}

void loadMedia()
{
    font = TTF_OpenFont("fzpix.ttf", 20);
}
int main(int argc, char *argv[])
{
    if (!init())
    {
        printf("init error!\n");
    }
    else
    {
        loadMedia();
        SDL_SetRenderDrawColor(render, 0, 0, 255, 255);

        SDL_RenderClear(render);
        setTextTexture(&txtText1, font, "你好");
        txtText1.txtDstRect.x = 100;
        txtText1.txtDstRect.y = 100;
        SDL_RenderCopy(render, txtText1.txtText, NULL, &txtText1.txtDstRect);
        SDL_RenderPresent(render);
        SDL_Delay(4000);

        SDL_DestroyRenderer(render);
        SDL_DestroyWindow(window);
        TTF_Quit();
        SDL_Quit();
    }
    return 0;
}